﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.Data;
using WLFramework.DataAccess;
using WLFramework.Json;
using WLFramework.Validation;
using WLFramework.Web;

namespace SampleSite.admin.ajax
{
    /// <summary>
    /// updateMenu 的摘要说明
    /// </summary>
    public class updateMenu : AjaxHttpHandler
    {
        private class InputData 
        {
            [Required]
            public int id { get; set; }

            [Required]
            public int AppId { get; set; }

            [Required]
            public int GroupId { get; set; }

            [Required]
            public string MenuName { get; set; }

            [Required]
            public string MenuUrl { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            InputData input;
            var errors = context.GetModel<InputData>(out input);
            if (errors.Count > 0)
                throw new Exception("输入的数据格式不正确");

            using (PermissionContext db = new PermissionContext())
            {
                var menu = db.sys_ModuleList.Where(k => k.M_ID == input.id &&
                                                        k.M_ParentID == input.GroupId &&
                                                        k.M_State == 1)
                                            .FirstOrDefault();
                if (menu == null)
                    throw new ArgumentNullException("menu");

                if (db.sys_ModuleList.Where(
                        k => k.M_AppID == input.AppId &&
                             k.sysModuleListsysApplications.A_State == 1 &&
                             k.M_ID == input.GroupId &&
                             k.M_State == 1).Count() == 1)
                {
                    var cmd = DataAccessor.CreateInstance<PermissionCommand>(db);
                    cmd.BeginTransaction();
                    var result = cmd.UpdateModule(
                        input.id,
                        input.MenuName,
                        menu.M_EName,
                        input.MenuUrl,
                        menu.M_IsEdit,
                        menu.M_Icon);

                    if (result.ErrorID != 0)
                        throw new Exception(result.ErrorMsg);

                    cmd.CommitTransaction();

                    context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
                }
                else
                {
                    throw new Exception("输入的数据格式不正确");
                }
            }
        }
    }
}